package com.tacademy.android.lbs.location;

import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.tacademy.android.lbs.PMF;
import com.tacademy.android.lbs.location.model.Place;

public class LocationService {
	
	public List<Place> getAllPlaces() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			StringBuilder query = new StringBuilder("select from ");
			query.append(Place.class.getName());
			query.append("  order by date desc");
			
			@SuppressWarnings("unchecked")
			List<Place> places = (List<Place>)pm.newQuery(query.toString()).execute();
			return (List<Place>) pm.detachCopyAll(places);
		} finally {
			pm.close();
		}
	}

	public Place getPlace(String placeId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			StringBuilder query = new StringBuilder("select from ");
			query.append(Place.class.getName());
			query.append("  where placeId == '").append(placeId).append("'");
			@SuppressWarnings("unchecked")
			List<Place> places = (List<Place>)pm.newQuery(query.toString()).execute();
			if (places.size() == 0) {
				return null;
			}
			Place place = places.get(0);
			
			return pm.detachCopy(place);			
		} finally {
			pm.close();
		}
	}
	
	public void savePlace(Place place) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			place.setCount(1);
			place.setDate(new Date());
			StringBuilder query = new StringBuilder("select from ");
			query.append(Place.class.getName());
			query.append("  where placeId == '").append(place.getPlaceId()).append("'");
			
			@SuppressWarnings("unchecked")
			List<Place> places = (List<Place>)pm.newQuery(query.toString()).execute();
			if (places.size() > 0) {
				Place storedPlace = places.get(0);
				place.setCount(storedPlace.getCount() + 1);
				place.setKey(storedPlace.getKey());
			}
			pm.makePersistent(place);
		} finally {
			pm.close();
		}
	}
}
